/*
 * Copyright (C) 2008 Universidade Federal de Campina Grande
 *  
 * This file is part of OurGrid. 
 *
 * OurGrid is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free 
 * Software Foundation, either version 3 of the License, or (at your option) 
 * any later version. 
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT 
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
 * for more details. 
 * 
 * You should have received a copy of the GNU Lesser General Public License 
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package org.ourgrid.broker.controller;

import java.util.ArrayList;
import java.util.List;

import org.ourgrid.broker.BrokerConstants;
import org.ourgrid.broker.commands.CommandExecutor;
import org.ourgrid.broker.commands.SchedulerData;
import org.ourgrid.broker.controller.messages.BrokerControlMessages;
import org.ourgrid.broker.dao.JobDAO;
import org.ourgrid.broker.dao.PeerDAO;
import org.ourgrid.broker.dao.PeerEntry;
import org.ourgrid.broker.scheduler.SchedulerIF;
import org.ourgrid.common.interfaces.LocalWorkerProvider;
import org.ourgrid.common.interfaces.LocalWorkerProviderClient;
import org.ourgrid.reqtrace.Req;

import br.edu.ufcg.lsd.commune.api.FailureNotification;
import br.edu.ufcg.lsd.commune.api.InvokeOnDeploy;
import br.edu.ufcg.lsd.commune.api.RecoveryNotification;
import br.edu.ufcg.lsd.commune.container.ObjectDeployment;
import br.edu.ufcg.lsd.commune.container.servicemanager.ServiceManager;
import br.edu.ufcg.lsd.commune.identification.DeploymentID;
import br.edu.ufcg.lsd.commune.network.xmpp.XMPPProperties;

/**
 *
 */
public class LocalWorkerProviderNotificationController {

	private ServiceManager serviceManager;

	@InvokeOnDeploy
	public void init(ServiceManager serviceManager) {
		this.serviceManager = serviceManager;
	}
	
	@Req("REQ328")
	@FailureNotification
	public void doNotifyFailure(LocalWorkerProvider monitorable, DeploymentID failedLocalWorkerProviderID) {
		
		PeerEntry peerEntry = serviceManager.getDAO(PeerDAO.class).getPeerEntry(
				failedLocalWorkerProviderID.getContainerID());
		
		if (peerEntry == null) {
			serviceManager.getLog().warn(BrokerControlMessages.getNoPeerWithSuchEntityIDMessage(failedLocalWorkerProviderID));
			return;
		} else if (peerEntry.isDown()){
			serviceManager.getLog().warn(BrokerControlMessages.getPeerAlreadyDownMessage(failedLocalWorkerProviderID));
			return;
		} 
		
		peerEntry.setAsDown();
		unbindLocalWorkerProviderClient();
		serviceManager.getLog().debug(BrokerControlMessages.getPeerIsDownMessage(failedLocalWorkerProviderID));
		
		List<SchedulerData> outputCommands = new ArrayList<SchedulerData>();
		
		for(SchedulerIF scheduler: serviceManager.getDAO(JobDAO.class).getSchedulers()) {
			List<SchedulerData> cjData = scheduler.localWorkerProviderFailure(failedLocalWorkerProviderID.toString());
			outputCommands.addAll(cjData);
		}
		
		CommandExecutor.getInstance().execute(outputCommands, serviceManager);
	}

	@Req("REQ327")
	@RecoveryNotification
	public void doNotifyRecovery(LocalWorkerProvider monitorableStub, DeploymentID recoveredLocalWorkerProviderID) {
		
		PeerEntry peerEntry = serviceManager.getDAO(PeerDAO.class).getPeerEntry(
				recoveredLocalWorkerProviderID.getContainerID());
		
		if (peerEntry == null) {
			serviceManager.getLog().warn(BrokerControlMessages.getNoPeerWithSuchEntityIDMessage(recoveredLocalWorkerProviderID));
		}
		
		peerEntry.setAsUp(monitorableStub);
		
		LocalWorkerProviderClient lwpc = getLocalWorkerProviderClient();
		monitorableStub.login(lwpc, 
				serviceManager.getContainerContext().getProperty(XMPPProperties.PROP_PASSWORD));
		
		serviceManager.getLog().debug(BrokerControlMessages.getPeerIsUpMessage(recoveredLocalWorkerProviderID));
	}

	/**
	 * Unbinds the Local Worker Provider Client Receiver if there is no peer up.
	 */
	private void unbindLocalWorkerProviderClient() {
		if (!serviceManager.getDAO(PeerDAO.class).hasPeerUp()) {
			serviceManager.undeploy(BrokerConstants.LOCAL_WORKER_PROVIDER_CLIENT);
		}
	}
	
	/**
	 * Creates the LocalWorkerProvider Receiver if it does not exist.
	 * @return The LocalWorkerProviderReceiver
	 */
	private LocalWorkerProviderClient getLocalWorkerProviderClient() {
		
		ObjectDeployment objectDeployment = serviceManager.getObjectDeployment(BrokerConstants.LOCAL_WORKER_PROVIDER_CLIENT);
		if (objectDeployment == null) {
			serviceManager.deploy(BrokerConstants.LOCAL_WORKER_PROVIDER_CLIENT, new LocalWorkerProviderClientController());
			return (LocalWorkerProviderClient) serviceManager.getObjectDeployment(BrokerConstants.LOCAL_WORKER_PROVIDER_CLIENT).getObject();
		}

		LocalWorkerProviderClient lwpc = (LocalWorkerProviderClient) objectDeployment.getObject();
		
		if (lwpc == null) {
			serviceManager.deploy(BrokerConstants.LOCAL_WORKER_PROVIDER_CLIENT, new LocalWorkerProviderClientController());
			return (LocalWorkerProviderClient) objectDeployment.getObject();
		}
		
		return (LocalWorkerProviderClient) lwpc;
	}

}
